<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/8/25
 * Time: 15:07
 */

namespace Home\Controller;


use Common\Utils\Constants;
use Home\Logic\RaceLogic;

class RaceController extends BaseController
{
    public function index(){
        $this->display();
    }

    public function detail(){
        $race_id = I('race_id');
        $logic = new RaceLogic();
        $race = $logic->getRaceById($race_id);
        $involved = D('ApplyLog')->where(array('race_id'=>$race_id))->count();
        $user = $this->getUser();
        $is_involved = D('ApplyLog')->where(array('race_id'=>$race_id,'user_id'=>$user['id']))->count();
        $now = time();


        if($race['status'] == Constants::RACE_STATUS_APPLY_START){
            $time_left = time_left($now, $race['apply_end_time']);
            $time = $race['apply_end_time'] - $now;

        }else{
            $time_left = '报名已经截止';
            $time = 0;
        }
        if($time <0){
            $time = 0;
        }
        $this->assign('race',$race);
        $this->assign('time',$time);
        $this->assign('involved',$involved);
        $this->assign('is_involved',$is_involved);
        $this->assign('time_left',$time_left);
        $this->display();
    }

    /**
     * 显示赛事群二维码
     */
    public function qrCode(){
        $race_id = I('race_id');
        $race = D('Race')->where(array('id'=>$race_id))->find();
        $this->assign('qr_code',$race['qr_code']);
        $this->display();
    }

    /**
     * ajax获取赛事列表
     */
    public function ajaxRaceList(){
        $pagesize = 10;
        $pagenumber = I('pagenum', '1');
        $logic = new RaceLogic();
        $data = $logic->getRaceList(null,$pagenumber,$pagesize);
        $this->assign('data', $data);
        $this->display('ajaxRaceList');
    }

    /**
     * 赛事报名
     */
    public function apply(){
        $race_id = I('race_id');
        $logic = new RaceLogic();
        $user = $this->getUser();
        $result = $logic->apply($user['id'],$race_id);
        $success = false;
        $code = -1;
        $data = array();
        switch ($result){
            case 0:
                $message = '报名失败！';
                break;
            case 1:
                $success = true;
                $message = '报名成功！';
                $involved = D('ApplyLog')->where(array('race_id'=>$race_id))->count();
                $data['involved'] = $involved;
                break;
            case 2:
                $message = '对不起，当前不是报名的时间！';
                break;
            case 3:
                $message = '对不起，您的钻石数目不足！';
                $code = Constants::CODE_INTEGRAL_INSUFFICIENT;
                break;
            case 4:
                $message = '对不起，报名人数已满！';
                break;
        }
        $this->ajax($success,$message,$code,$data);
    }

}